/* Copyright (c) 2010 Fabian Kulman
* 
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* 
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* 
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

#include <stdio.h>
#include <stdlib.h>
#include <cmath>
#include <iostream>

using namespace std;

#include "gui.h"

void gui::callBackKeypress(unsigned char key, int x, int y) {    
	switch (key) {
		//case 'h':
		//	SPACE_OPTIONS.drawHash = !SPACE_OPTIONS.drawHash;
		//	break;
		case 'b':
			SPACE_OPTIONS.drawBBs = !SPACE_OPTIONS.drawBBs;
			break;
		case 'p':
			space->chain->printChainState();
			break;
	}
}


void gui::callBackActiveMotion(int x, int y){
	space->mousePoint = mouseToSpace(x, y);
	glutSetCursor(GLUT_CURSOR_INFO);
	mouseHasMoved = true;

	MOUSE_X = (GLfloat)x*0.75;
	MOUSE_Y = (GLfloat)y*0.75;
}


void gui::callBackPassiveMotion(int x, int y){
	space->mousePoint = mouseToSpace(x, y);
	glutSetCursor(GLUT_CURSOR_RIGHT_ARROW);

	MOUSE_X = (GLfloat)x*0.75;
	MOUSE_Y = (GLfloat)y*0.75;
}


void gui::callBackMouseClick(int button, int state, int x, int y){

	// Scaling
	if ( button == GLUT_WHEEL_UP ){
		SPACE_OPTIONS.scaleFactor += 0.1;
		return;
	}
	else if( button == GLUT_WHEEL_DOWN ){
		SPACE_OPTIONS.scaleFactor -= 0.1; 
		if (SPACE_OPTIONS.scaleFactor < 0.0){ SPACE_OPTIONS.scaleFactor = 0.0;};
		return;
	}


	if(button == GLUT_LEFT_BUTTON){
		if(state == GLUT_DOWN){

			mouseIsActive = true;
			mouseHasMoved = false;

			if(activeUnit != NULL && activeUnit->lu){
				space->chain->stopDragRotation( activeUnit );
			}

			cpVect point = mouseToSpace(x, y);
			activeUnit = space->chain->pointInChain(point);

			if(activeUnit != NULL && activeUnit->lu ){
				cpBody* body = activeUnit->body;
				mouseJoint = cpPivotJointNew2(space->mouseBody, body, cpvzero, cpBodyWorld2Local(body, point));
				mouseJoint->maxForce = 500000.0f;
				mouseJoint->biasCoef = 0.15f;
				cpSpaceAddConstraint(space->activeSpace, mouseJoint);

				space->chain->startDragRotation( activeUnit );
			}
		} 

		if(state == GLUT_UP){

			mouseIsActive = false;

			if(mouseJoint){
				cpSpaceRemoveConstraint(space->activeSpace, mouseJoint);
				cpConstraintFree(mouseJoint);
				mouseJoint = NULL;
			}
			if(activeUnit){
				if(activeUnit->lu){
					activeUnit->snap();
				}

				/* // Snap rotation
				if( !mouseHasMoved && activeUnit->ru ){ // && activeUnit != *(space->chain->vUnit.end()-1) ){
					cout << "snap" << endl;
					if(activeUnit->lu){
						space->chain->stopDragRotation( activeUnit );
					}
					activeUnit = activeUnit->ru;
					space->chain->startDragRotation( activeUnit );
					space->chain->snapRotation( activeUnit );
				}
				*/
			}
			
		}
		cpSpaceRehashStatic( space->activeSpace );
		space->chain->stopChain();
	}

	// Rotates the chain for 36 degrees
	if(button == GLUT_RIGHT_BUTTON){
		if(state == GLUT_DOWN){
			if(RO_ANGLE >= 360){
				RO_ANGLE -= 360;
			}
			RO_ANGLE += 36; 
		}	
	}
}


void gui::callBackResize(int w, int h) {
		WINDOW_HEIGHT = h;
		WINDOW_WIDTH = w;
}


void gui::callBackDisplay(void){

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
	glMatrixMode(GL_PROJECTION); 
	glLoadIdentity();


	// Scale
	GLfloat scW = (GLfloat)WINDOW_WIDTH/2.0 * SPACE_OPTIONS.scaleFactor; 
	GLfloat scH = (GLfloat)WINDOW_HEIGHT/2.0 * SPACE_OPTIONS.scaleFactor; 

	glOrtho(-scW, scW, -scH, scH, 5.0f, -5.0f);		


	// Translation
	if(mouseIsActive == true && (activeUnit == NULL || activeUnit == space->chain->vUnit[0]) ){
		GLfloat dx = MOUSE_X - MOUSE_OLD_X; 
		TR_X = TR_X + dx; 

		GLfloat dy = MOUSE_Y - MOUSE_OLD_Y; 
		TR_Y = TR_Y + dy; 
	}

	TR_X = floor(TR_X + 0.5);
	TR_Y = floor(TR_Y + 0.5);
	glTranslatef(TR_X, -TR_Y, 0.0f);

	MOUSE_OLD_X = MOUSE_X;
	MOUSE_OLD_Y = MOUSE_Y;
		

	// Rotation
	glRotatef(RO_ANGLE, RO_X, RO_Y, RO_Z);


	// Drawing
	space->drawSpace(space->activeSpace, &SPACE_OPTIONS);


	// Update Buffer
	glutSwapBuffers();
	space->ticks++;


	// Update mouse
	cpVect newPoint = cpvlerp(space->oldMousePoint, space->mousePoint, 0.25f);
	space->mouseBody->p = newPoint;
	space->mouseBody->v = cpvmult(cpvsub(newPoint, space->oldMousePoint), 60.0f);
	space->oldMousePoint = newPoint;

	space->updateSpace(space->ticks);
	glutPostRedisplay();	


	// Stops all movement, as soon as there are no intersections anymore
	if( space->activeSpace->arbiters->num == 0 && mouseIsActive == false && mouseHasMoved ){
		space->chain->stopChain();
	}
	else if( space->activeSpace->arbiters->num > 2 && mouseIsActive == false && mouseHasMoved ){
		if(activeUnit){
			activeUnit->unlookJoint();
		}
	}

	// Snaps at the end of a snap rotation
	if( activeUnit && !mouseHasMoved && !mouseIsActive ){
		mouseHasMoved = activeUnit->snap();
	}
}

void gui::destroy(){
	delete space;
}

void gui::initOpenGl(){
	glClearColor(1.0f, 1.0f, 1.0f, 0.0f);

	glEnableClientState(GL_VERTEX_ARRAY);
	glEnable(GL_LINE_SMOOTH);
	glEnable(GL_POINT_SMOOTH);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
	glHint(GL_POINT_SMOOTH_HINT, GL_DONT_CARE);
}


void gui::initGLUT( int argc, char** argv, std::vector<cpFloat>* input ){
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB); //| GLUT_DEPTH);

	glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); 
	glutInitWindowPosition(WINDOW_POSITION_X, WINDOW_POSITION_Y);
	glutCreateWindow("Folding Robot");

	space = new Space( input );
	initOpenGl();

	glutDisplayFunc(callBackDisplay);
	glutReshapeFunc(callBackResize);

	glutIgnoreKeyRepeat(1);
	glutKeyboardFunc(callBackKeypress);

	glutMotionFunc(callBackActiveMotion);
	glutPassiveMotionFunc(callBackPassiveMotion);
	glutMouseFunc(callBackMouseClick);

	atexit(destroy);
}

/* 
* Copyright (c) 2007 Scott Lembcke (MIT License)
*/
cpVect gui::mouseToSpace( int x, int y ){
	GLdouble model[16];
	glGetDoublev(GL_MODELVIEW_MATRIX, model);

	GLdouble proj[16];
	glGetDoublev(GL_PROJECTION_MATRIX, proj);

	GLint view[4];
	glGetIntegerv(GL_VIEWPORT, view);

	GLdouble mx, my, mz;
	gluUnProject(x, glutGet(GLUT_WINDOW_HEIGHT) - y, 0.0f, model, proj, view, &mx, &my, &mz);

	return cpv(mx, my);
}
